
package com.joolun.cloud.pay.api.config;

import com.alipay.easysdk.factory.MultipleFactory;
import com.alipay.easysdk.kernel.Config;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.joolun.cloud.pay.api.service.PayConfigService;
import com.joolun.cloud.pay.common.constant.PayConstants;
import com.joolun.cloud.pay.common.entity.PayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * 微信支付Configuration
 * @author www.joolun.com
 *
 */
@Slf4j
@Configuration
public class AliPayConfiguration {

	private static PayConfigService payConfigService;

	@Autowired
	public AliPayConfiguration(PayConfigService payConfigService) {
		this.payConfigService = payConfigService;
	}

	/**
	 * 获取Factory
	 * @return
	 */
	public static MultipleFactory getFactory() throws Exception {
		MultipleFactory multipleFactory = new MultipleFactory();
		multipleFactory.setOptions(getOptions());
		return multipleFactory;
	}

	private static Config getOptions() throws Exception {
		PayConfig payConfig = payConfigService.getOne(Wrappers.<PayConfig>query().lambda()
				.eq(PayConfig::getType, PayConstants.PAY_TYPE_2));
		if(payConfig == null){
			throw new Exception("当前租户没有配置支付宝");
		}
		Config config = new Config();
		config.protocol = "https";
		config.gatewayHost = "openapi.alipay.com";
		config.signType = "RSA2";
		config.appId = payConfig.getAppId();

		// 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
		config.merchantPrivateKey = payConfig.getMchKey();

		//注：证书文件路径支持设置为文件系统中的路径或CLASS_PATH中的路径，优先从文件系统中加载，加载失败后会继续尝试从CLASS_PATH中加载
		//请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt
		config.merchantCertPath = payConfig.getPrivateCertPath();
		//请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt
		config.alipayCertPath = payConfig.getPrivateKeyPath();
		//请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt
		config.alipayRootCertPath = payConfig.getKeyPath();

		//注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
		// config.alipayPublicKey = "<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->";

		return config;
	}
}
